<template>
    <div class="jianzhan-content">
        <Crumb :name="$t('employee.employee')"/>
        <div class="content">
            <el-button size="small" type="primary" @click="open">{{$t('add')}}</el-button>
            <Search>
                <el-input v-model="key" class="input" size="small" :placeholder="$t('employee.search')"
                          prefix-icon="el-icon-search"/>
            </Search>
            <div class="table-wrapper">
                <el-table
                        border
                        row-key="id"
                        stripe
                        :data="list.slice((pageNum-1)*pageSize,pageNum*pageSize)"
                >
                    <el-table-column
                            type="expand"
                    >
                        <template slot-scope="scope">
                            <el-card class="box-card" style="width: 50%">
                                <div slot="header" class="clearfix">
                                    <div class="imgAvatar"
                                         style="display: inline-block;width: 80px;height: 80px;overflow: hidden;border-radius:50% ">
                                        <img :src="scope.row.imageUrl" :alt="scope.row.employeeName" width="100%"
                                             height="100%">
                                    </div>
                                    <div class="text-container">
                                        <span>{{scope.row.employeeName}}/{{scope.row.employeeNum}}</span>
                                        <div>{{scope.row.handPhone}}</div>
                                        <div>{{scope.row.alamat}}</div>
                                    </div>
                                    <div class="qr-code"></div>
                                </div>
                                <div class="box">
                                    <div class="title">{{$t('employee.title')}}</div>
                                    <div class="text-content">{{scope.row.positionName}}</div>
                                </div>
                                <div class="box">
                                    <div class="title">{{$t('employee.manager')}}</div>
                                    <div class="text-content">{{scope.row.manager}}</div>
                                </div>
                                <div class="box">
                                    <div class="title">{{$t('employee.onBoard')}}</div>
                                    <div class="text-content">{{scope.row.contractStartDateStr}}</div>
                                </div>
                                <div class="box">
                                    <div class="title">{{$t('employee.ktp')}}</div>
                                    <div class="text-content">{{scope.row.nomorKtp}}</div>
                                </div>
                                <div class="box">
                                    <div class="title">{{$t('employee.kk')}}</div>
                                    <div class="text-content">{{scope.row.noKk}}</div>
                                </div>
                                <div class="box">
                                    <div class="title">{{$t('employee.agama')}}</div>
                                    <div class="text-content">{{scope.row.agama}}</div>
                                </div>
                                <div class="box">
                                    <div class="title">{{$t('employee.pendid')}}</div>
                                    <div class="text-content">{{scope.row.pendidikan}}</div>
                                </div>
                                <div class="box">
                                    <div class="title">{{$t('employee.birthday')}}</div>
                                    <div class="text-content">{{scope.row.birthday}}</div>
                                </div>
                                <div class="box">
                                    <div class="title">{{$t('employee.bankCard')}}</div>
                                    <div class="text-content">{{scope.row.bankCardNumber}}</div>
                                </div>
                            </el-card>
                        </template>
                    </el-table-column>
                    <el-table-column prop="employeeName" :label="$t('employee.employeeName')"/>
                    <el-table-column prop="positionName" :label="$t('employee.title')" :filters="positionNameFilters"
                                     :filter-method="handleFilter"/>
                    <el-table-column prop="manager" :label="$t('employee.manager')" :filters="managerFilters"
                                     :filter-method="handleFilter"/>
                    <el-table-column prop="employeeNum" :label="$t('employee.employeeId')"/>
                    <!--<el-table-column prop="email" label="Email"/>-->
                    <el-table-column prop="handPhone" :label="$t('employee.handPhone')"/>
                    <el-table-column prop="contractStartDateStr" :label="$t('employee.onBoard')"/>
                    <el-table-column label="Operate" width="220">
                        <template slot-scope="employee">
                            <el-button @click="showDetail(employee.row)" size="small">{{$t('edit')}}</el-button>
                            <el-button @click="deleteEmp(employee.row)" size="small" type="danger">{{$t('delete')}}
                            </el-button>
                            <el-button type="text" @click="showWork(employee.row)">{{$t('employee.show')}}</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="page">
                    <el-pagination background
                                   :page-size="pageSize"
                                   @current-change="changePage"
                                   layout="prev, pager, next"
                                   :total="total"/>
                </div>
            </div>
        </div>
        <el-dialog :visible.sync="dialogVisible" :title="$t('employee.employee')" width="80%">
            <el-form :model="employee" ref="employeeForm" label-width="200px">
                <el-form-item required :label="$t('employee.employeeName')">
                    <el-input size="small" v-model="employee.employeeName"/>
                </el-form-item>
                <el-form-item required :label="$t('employee.title')">
                    <el-cascader
                            :options="data1"
                            style="width: 250px;"
                            :show-all-levels="false"
                            :props="{
                                checkStrictly:true,
                                value:'id',
                                label:'position',
                                children:'manPowerServiceStationDtoList'
                            }"
                            v-model="employee.position"
                    ></el-cascader>
                </el-form-item>
                <el-form-item :label="$t('employee.manager')">
                    <el-input size="small" v-model="employee.manager"/>
                </el-form-item>
                <el-form-item required :label="$t('employee.employeeId')">
                    <el-input size="small" v-model="employee.employeeNum"/>
                </el-form-item>
                <el-form-item :label="$t('employee.workshop')">
                    <el-input size="small" v-model="employee.placeAtWorkshop"/>
                </el-form-item>
                <el-form-item :label="$t('employee.handPhone')">
                    <el-input size="small" v-model="employee.handPhone"/>
                </el-form-item>
                <el-form-item required :label="$t('employee.onBoard')">
                    <el-date-picker v-model="employee.contractStartDateStr" style="width: 100%" size="small"
                                    value-format="yyyy-MM-dd"/>
                </el-form-item>
                <el-form-item :label="$t('employee.ktp')">
                    <el-input size="small" v-model="employee.nomorKtp"/>
                </el-form-item>
                <el-form-item :label="$t('employee.kk')">
                    <el-input size="small" v-model="employee.noKk"/>
                </el-form-item>
                <el-form-item :label="$t('employee.birthday')">
                    <el-input size="small" v-model="employee.birthday"/>
                </el-form-item>
                <el-form-item :label="$t('employee.pendid')">
                    <el-input size="small" v-model="employee.pendidikan"/>
                </el-form-item>
                <el-form-item :label="$t('employee.agama')">
                    <el-input size="small" v-model="employee.agama"/>
                </el-form-item>
                <el-form-item :label="$t('employee.merry')">
                    <el-input size="small" v-model="employee.maritalStatus"/>
                </el-form-item>
                <el-form-item :label="$t('employee.address')">
                    <el-input size="small" v-model="employee.alamat"/>
                </el-form-item>
                <el-form-item :label="$t('employee.workExp')">
                    <el-input size="small" v-model="employee.workingExperience"/>
                </el-form-item>
                <el-form-item :label="$t('employee.bankCard')">
                    <el-input size="small" v-model="employee.bankCardNumber"/>
                </el-form-item>
                <el-form-item label="ImageUrl">
                    <label for="avatar">{{$t('employee.avatar')}}</label>
                    <input type="file" v-show="false" id="avatar" ref="avatar" @change="fileChange">
                    <div class="avator-preview">
                        <img :src="employee.imageUrl" width="100%" height="100%" alt="">
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">{{$t('cancel')}}</el-button>
                        <el-button type="primary" @click="submitForm">{{$t('confirm')}}</el-button>
                    </span>
        </el-dialog>

        <el-dialog
                title="Work Detail"
                :visible.sync="dialogVisible1"
                top="0"
                width="100%"
               >
            <el-select v-model="month" placeholder="Month" style="float: left;margin-bottom: 10px;" size="small">
                <el-option
                        v-for="item in 12"
                        :key="item"
                        :label="item"
                        :value="item">
                </el-option>
            </el-select>
            <el-table
                    :data="employeeWork"
                    border
                    stripe
                    style="width: 100%">
                <el-table-column
                        prop="workingNo"
                        label="No"
                        >
                </el-table-column>
                <el-table-column
                        prop="workingNumber"
                        label="Wo"
                        >
                </el-table-column>
                <el-table-column
                        label="pointCode">
                    <template slot-scope="row">
                        <span>{{row.row.serviceItemVoList[0].pointCode}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                        label="Description">
                    <template slot-scope="row">
                        <span>{{row.row.serviceItemVoList[0].serviceItem}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                        label="Hours">
                    <template slot-scope="row">
                        <span>{{row.row.serviceItemVoList[0].hours}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="elapsedTime"
                        label="Real hours"
                >
                </el-table-column>
                <el-table-column
                        prop="numberOfWork"
                        label="Man Power"
                >
                </el-table-column>
                <el-table-column
                        prop="totalSalary"
                        label="share"
                >
                </el-table-column>
                <el-table-column
                        prop="avgSalary"
                        label="Avg"
                >
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible1 = false">close</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
    import {mapGetters, mapActions, mapMutations} from 'vuex'
    import mixins from '../../util/mixins'
    import Crumb from '@/components/common/crumb'
    import Search from '@/components/common/search'
    import {addEmployee, deleteEmployee, getHumanResource, modEmplyee, upLoadFiles} from "../../api";
    import {ERROR_OK} from "../../util/config";
    import {arrayUnique, getArray} from "../../util";
    import {getDepartmentList} from "../../api/auth";
    import {clear} from "../../util";
    import {getEmployeeWork} from "../../api/service";

    export default {
        name: "employee",
        mixins: [mixins],
        data() {
            return {
                data1:{},
                id:'',
                month:new Date().getMonth()+1,
                positionNameFilters: [],
                managerFilters: [],
                key: '',
                employeeWork:[],
                employee: {
                    id: '',
                    employeeName: '',
                    position: '',
                    manager: '',
                    employeeNum: '',
                    placeAtWorkshop: '',
                    handPhone: '',
                    contractStartDateStr: '',
                    nomorKtp: '', //身份证
                    noKk: '',
                    birthday: '',
                    pendidikan: '', //受教育
                    agama: '',    //宗教
                    maritalStatus: '',//婚宴
                    alamat: '',   //地址
                    workingExperience: '',
                    bankCardNumber: '',
                    imageUrl: '',
                },
                dialogVisible: false,
                dialogVisible1: false,
                departmentList: []
            }
        },
        created() {
            this.loadEmployeeList();
            this.getHuman()
            this._getDepartment();
        },
        computed: {
            spreadDeptList() {
                return getArray(this.departmentList)
            },
            list() {
                return this.employeeList.filter(item => item.employeeName.toLowerCase().indexOf(this.key.toLowerCase()) > -1)
            },
            ...mapGetters(['employeeList'])
        },
        mounted() {
            this.total = this.list.length;
            ['manager','position'].forEach(item=>{
                this[item+'Filters'] = arrayUnique(this.employeeList.map(
                    e => {
                        return e[item]
                    }
                )).map(i=>{
                    return {
                        text:i,
                        value:i
                    }
                })
            });
        },
        methods: {
            async getHuman(){
                const {status,data} = await getHumanResource();
                if(status===ERROR_OK){
                    this.data1 = data[0]
                }
            },
            async showWork(row){
                this.id = row.id;
                const {status,data,msg} = await getEmployeeWork(row.id);
                if(status === ERROR_OK) {
                    this.employeeWork = data
                    this.dialogVisible1 = true
                }else {
                    this.$message.error(msg)
                }
            },
            async showWorkByMonth(month){
                const {status,data,msg} = await getEmployeeWork(this.id,month);
                if(status === ERROR_OK) {
                    this.employeeWork = data
                    this.dialogVisible1 = true
                }else {
                    this.$message.error(msg)
                }
            },
            handleFilter(value, row, column) {
                const p = column['property']
                return row[p] === value
            },
            async fileChange(e) {
                const formData = new FormData();
                Array.prototype.forEach.call(e.target.files, item => {
                    formData.append('upload_file', item)
                });
                const {success, file_path} = await upLoadFiles(formData);
                if (success) {
                    this.$set(this.employee, 'imageUrl', file_path[0])
                }
                this.$nextTick(() => {
                    this.$refs.avatar.value = '';
                })
            },
            async _getDepartment() {
                let {status, data} = await getDepartmentList();
                if (status === ERROR_OK) {
                    this.departmentList = data
                }
            },
            open() {
                this.dialogVisible = true;
                clear();
            },

            submitForm() {
                this.$refs.employeeForm.validate(async valid => {
                    if (valid) {
                        let e = {...this.employee};
                        if(e.position && e.position.length){
                            e.position = e.position[e.position.length-1]
                        }
                        delete e.contractStartDate;
                        if (e.id) {
                            const {status} = await modEmplyee(e);
                            if (status === ERROR_OK) {
                                this.modEmployee(this.employee);
                                this.loadEmployeeList(true)
                                this.dialogVisible = false
                            }
                        } else {
                            const {status, data} = await addEmployee(e);
                            if (status === ERROR_OK) {
                                this.employee.id = data.id;
                                this.addEmployee(this.employee);
                                this.loadEmployeeList(true);
                                this.dialogVisible = false
                            }
                        }
                    }
                })
            },
            deleteEmp(employee) {
                this.$confirm(
                    'Do you want to delete this employee ?'
                ).then(async () => {
                    const {status} = await deleteEmployee(employee.id);
                    if (status === ERROR_OK) {
                        this.deleteEmployee(employee);
                    }
                }).catch(() => {

                })
            },
            showDetail(employee) {
                this.employee = employee;
                this.dialogVisible = true
            },
            ...mapMutations(['addEmployee', 'modEmployee', 'deleteEmployee']),
            ...mapActions(['loadEmployeeList']),
        },
        watch: {
            list(list) {
                this.total = list.length;
            },
            employeeList(){
                ['manager','positionName'].forEach(item=>{
                    this[item+'Filters'] = arrayUnique(this.employeeList.map(
                        e => {
                            return e[item]
                        }
                    )).map(i=>{
                        return {
                            text:i,
                            value:i
                        }
                    })
                });
            },
            month(){
                this.showWorkByMonth(this.month)
            }
        },
        components: {
            Crumb, Search
        }
    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";

    .content {
        @include content
    }

    .text-container {
        padding-left: 20px;
        display: inline-block;
        vertical-align: top;
        span {
            font-size: 18px;
            font-weight: 400;
        }
    }

    .box {
        border-bottom: 1px solid #ddd;
        padding: 10px 0;
    }

    .title {
        width: 200px;
        display: inline-block;
        vertical-align: middle;
        font-size: 16px;
        margin-right: 10px;
        font-weight: 400;
    }

    .text-content {
        font-size: 14px;
        display: inline-block;
        vertical-align: middle;
    }

    .qr-code {
        float: right;
        width: 80px;
        height: 80px;
        overflow: hidden;
        border: 1px solid #ddd;
        margin-bottom: 10px;
    }

    label {
        width: 120px;
        height: 30px;
        padding: 15px;
        line-height: 30px;
        font-size: 14px;
        background: $bg-theme;
        border-radius: 5px;
        box-shadow: 2px 2px 2px #ddd;
        cursor: pointer;
        margin-top: 10px;
        text-align: center;
        color: white;
    }

    .avator-preview {
        width: 100px;
        overflow: hidden;
        height: 100px;
        border-radius: 50%;
        border: 1px solid #ddd;
        box-shadow: 2px 2px 2px #ddd, -2px -2px 2px #ddd;
        &:hover {
            transition: all 1s ease;
            transform: rotateY(360deg);
        }
    }
</style>